package lumis.service.wsrp.consumer.doui;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.doui.source.field.ISourceField;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.service.wsrp.consumer.IPortletServiceManager;
import lumis.service.wsrp.consumer.PortletServiceManagerFactory;
import lumis.service.wsrp.consumer.producermanager.ClonedPortlet;

import java.util.Collection;

import javax.persistence.EntityManager;
/**
 * ProcessActionHandler to remove unwanted cloned portlets.  This will run when the button "Remove Clone" is pressed.
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */ 

public class RemoveCloneProcessActionHandler extends ProcessActionHandler<Source<ISourceField>>
{

	/**
	 * ProcessAction to remove unwanted cloned portlets.  This will run when the button "Remove Clone" is pressed.
	 * @throws PortalException if the selected portlet is not a clone or if there are insterface instances using that clone.
	 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
	 * @since 6.0.0 
	 */
	public void processAction() throws PortalException 
	{
		
		String cloneHandle = getParameter("portletHandle", String.class);
		String producerEntityId = source.getDouiContext().getRequest().getServiceInstanceConfig().getId();
		
		IPortletServiceManager portletServiceManager = PortletServiceManagerFactory.getPortletServiceManager(producerEntityId);
		EntityManager entityManager = ManagerFactory.getEntityManager();
		
		//verifying if the handle passed belongs to a cloned portlet
		ClonedPortlet clonedPortlet = entityManager.find(ClonedPortlet.class, cloneHandle);
		if(clonedPortlet == null)
		{
			throw new PortalException("STR_WSRP_HANDLE_NOT_CLONE", getResource());
		}
		
		//verifying if no interface instance is using the clone.
		Collection<String> interfaceInstanceIds = clonedPortlet.getInterfaceInstanceIds();
		if(interfaceInstanceIds != null && !interfaceInstanceIds.isEmpty())
		{
			throw new PortalException("STR_WSRP_CLONE_BEING_USED", getResource());
		}
		
		//removes the remote and local clone 
		portletServiceManager.removeClone(cloneHandle);
	}

}
